<template>
	<view>
		<view v-if="showWave" class="layer flex-column">
			<wave />
		</view>
		<view
			@touchstart="onTouchStart"
			@touchend="onTouchEnd"
			class="textarea audio flex-column">
			按住 说话
		</view>
	</view>
</template>

<script>
import Wave from './wave.vue'
import XBCIM from 'xbcim'
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
export default{
	data(){
		return {
			showWave: false,
		}
	},
	onLoad() {
		// 监听录音结束
		recorderManager.onStop(res => {
			// 这里需要通过uni.uploadFile将音频文件上传到自己的服务器，并返回可访问的路径
			// 为考虑服务器资源问题，demo演示，这里固定一个测试音频地址，即上述url
			res.tempFilePath = 'https://cdn.xiangbaicheng.com/public/media/sound.mp3'
			innerAudioContext.src = res.tempFilePath
			innerAudioContext.onCanplay(() => {
				const duration = innerAudioContext.duration
				if(duration < 1){
					uni.showToast({
						icon: 'none',
						title: '录音时间太短'
					})
					return
				}
				setTimeout(() => {
					this.$emit('success', {
						duration,
						url: res.tempFilePath
					})
				  }, 500)
			})
		})
	},
	methods: {
		// 按住
		onTouchStart() {
			this.showWave = true
			recorderManager.start()
		},
		// 松开
		onTouchEnd() {
			this.showWave = false
			recorderManager.stop()
		}
	}
}
</script>

<style lang="scss" scoped>

.layer {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	z-index: 999;
}

.textarea {
	width: 100%;
	color: #333;
	font-size: 30rpx;
	max-height: 160px;
	padding-top: 20rpx;
	padding-bottom: 12rpx;
	background-color: #fff;
	
	&.audio {
		pointer-events: all;
		padding-top: 12rpx;
		@include fullsize();
		position: absolute;
		top: 0;
		left: 0;
	}
}
</style>